package com.kizuki.controller;

import com.kizuki.bo.CalInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@RestController
@Validated
public class MyController {

    @GetMapping("/hello")
    public String welcome(){
        return "welcome by visiting kizuki-springboot-annotation";
    }

    /**
     * http://localhost:8080/cal1/2
     */
    @GetMapping("/cal1/{num}")
    public int calculate1(@PathVariable Integer num){
        int res = num * num;
        log.info("服务器计算cal1结果：{}", res);
        return res;
    }

    /**
     * http://localhost:8080/cal2?num=2
     * 需要类加上@Validated注解才能验证参数
     */
    @GetMapping("/cal2")
    public int calculate2(@RequestParam(value = "num", required = false) @Valid @Min(1) Integer num){
        if (Objects.isNull(num)) {
            log.info("服务器获取数据失败");
            return 0;
        } else {
            int res = num * num;
            log.info("服务器计算cal2结果：{}", res);
            return res;
        }
    }

    /**
     * http://localhost:8080/cal3
     * Body raw json : {num:2}
     * 注解@Valid验证失败会抛MethodArgumentNotValidException
     */
    @PostMapping("/cal3")
    public String calculate3(@RequestBody  @Valid CalInfo calInfo, @RequestParam(value = "num", required = false) Integer num){
        log.info("服务器获得的参数num是：{}", num);
        log.info("服务器计算cal3结果：{}", calInfo.getResult());
        return calInfo.toString();
    }

    @Autowired
    private RestTemplate restTemplate;

    @ResponseBody
    @GetMapping("/1")
    public void test1(HttpServletResponse response) throws IOException {
        String url = "http://localhost:8080/1?response=" + response;
        byte[] bytes = restTemplate.getForObject(url, byte[].class);
        System.out.println(bytes);
//        response.getOutputStream().write(bytes);
    }

}
